package com.kamistoat.meimeimall.meimeimallseckill.scheduled;

import com.kamistoat.meimeimall.common.runTimeFunc.RunTimeLog;
import com.kamistoat.meimeimall.meimeimallseckill.service.SeckillSessionService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 促销活动缓存预热.
 */
@Service
public class SecKillSkuScheduled {
    protected Logger logger = LoggerFactory.getLogger(SecKillSkuScheduled.class);

    @Autowired
    SeckillSessionService seckillSessionService;
    @Autowired
    RedissonClient redissonClient;

    /**
     * 每天晚上3点执行改定时任务。cron表达式就是规定每天3点0分0秒
     * 测试期间使用每3分钟执行一次
     */
    // @Scheduled(cron = "0 0 3 * * ?")  // 每晚3点
    // @Scheduled(cron = "0 0/30 * * * ?")  // 每30分钟执行一次
    public void upload3DaySecKillSku() {
        logger.info("从缓存中删除已经过期一天的促销预热");
        seckillSessionService.deleteOneDaySecKill();
        logger.info("对未来三天内的促销活动执行预热");
        // 要先获取分布式锁，能获取到才会执行上架
        RLock lock = redissonClient.getLock("seckill:upload:lock");
        // 如果获取到分布式锁，则这个锁最长持有10秒，如果某个服务器执行上架失败，那么最晚10秒后，这个锁会被自动释放
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillSessionService.uploadThreeDaySecKill();
        } finally {
            lock.unlock();
        }
    }
}
